package io.spring.sample.graphql.util;



import java.io.*;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.UUID;

public class Tool {


    /**
     * 反射机制来获取单个对象指定键的值 ReflectObjectUtil
     * @param t
     * @param key 属性字段名字
     * @param <T> 对象类型
     * @return 实际类的字段类型定义型
     */
    public static <T> Object reflectGetValueByKey(T t, String key) {
        Class clazz = t.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Field resultField = Arrays.stream(fields)
                .filter(field -> field.getName().equals(key))
                .findFirst()
                .get();
        //没有该字段 .get()报错的;
        Object obj = null;
        resultField.setAccessible(true);
        try {
            obj = resultField.get(t);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return obj;
    }

}

